import { ComponentClass } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, ScrollView, Text, Image } from '@tarojs/components'
import { connect } from '@tarojs/redux'

import './index.scss'

import bannerImg from '../../asset/images/shop/banner.jpg'
import dividerImg from '../../asset/images/shop/divider.png'
import bossIcon from '../../asset/images/shop/boss-icon.png'
import businessIcon from '../../asset/images/shop/business-icon.png'
import carIcon from '../../asset/images/shop/car-icon.png'
import houseIcon from '../../asset/images/shop/house-icon.png'
import freeIcon from '../../asset/images/shop/free-icon.png'
import personIcon from '../../asset/images/shop/person-icon.png'
import salaryIcon from '../../asset/images/shop/salary-icon.png'
import workerIcon from '../../asset/images/shop/worker-icon.png'
import ProductFilter from '../../components/product-filter'
import ProductList from '../../components/product-list'

import { Utils } from '../../utils/utils'

import { isTimeIntervalValid, getNextPage } from '../../utils/pagination'

// #region 书写注意
// 
// 目前 typescript 版本还无法在装饰器模式下将 Props 注入到 Taro.Component 中的 props 属性
// 需要显示声明 connect 的参数类型并通过 interface 的方式指定 Taro.Component 子类的 props
// 这样才能完成类型检查和 IDE 的自动提示
// 使用函数模式则无此限制
// ref: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/20796
//
// #endregion

let cont_time = 0  //纪录极速贷，银行贷tab点击的时间
const utils = new Utils()

type PageStateProps = {
  activeTabIndex: number
  bankSearchCondition: any
  bankSearchOption: any,
  bankProductPage: number,
  bankProductList: any[],
  bankProductTotal: number,
  bankNoneResultTips: string,
  bankNoneResult: boolean,
  bankLastLoadTime: number,
  fastSearchCondition: any
  fastSearchOption: any,
  fastProductPage: number,
  fastProductList: any[],
  fastProductTotal: number,
  fastNoneResultTips: string,
  fastNoneResult: boolean,
  fastLastLoadTime: number,
  userApplyList: any[],
  effects: any,
  defaultPageSize: number,
}

type PageDispatchProps = {
  searchBank: (condition: any) => void,
  searchFast: (condition: any) => void,
  saveTabIndex: (tabIndex: number) => void,
}

type PageOwnProps = {}

type PageState = {
  // 页面Y轴滚动距离
  scrollTop: number,
  // 产品过滤组件固定定位高度
  filterFixTop: number
}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Shop {
  props: IProps;
  state: PageState;
}

@connect(({ shop, common, loading }) => ({
  ...shop,
  ...common,
  ...loading,
}), (dispatch) => ({
  searchBank(condition: any) {
    dispatch({
      type: 'shop/searchBank',
      payload: condition
    })
  },
  searchFast(condition: any) {
    dispatch({
      type: 'shop/searchFast',
      payload: condition
    })
  },
  saveTabIndex(tabIndex: number) {
    dispatch({
      type: 'common/save',
      payload: {
        activeTabIndex: tabIndex,
      }
    })
  }
}))
class Shop extends Component {

  constructor(props) {
    super(props);
    // this.state = {
    // searchOption: {
    //   deposit: depositFilterOptions[2],
    //   time_limit: timeFilterOptions[2],
    //   sort: sortFilterOptions[1],
    //   product_type: productTypeOptions[0],
    //   mortgage_type: mortgageTypeOptions[0],
    //   job: jobsOptions[0],
    // }
    // }
  }

  componentWillReceiveProps(nextProps) {

    const that = this

    // 银行搜索条件改变的情况下，重新加载产品
    const nextBankSearchCondition = nextProps.bankSearchCondition
    const currBankSearchCondition = that.props.bankSearchCondition
    if (nextBankSearchCondition && currBankSearchCondition
      && JSON.stringify(nextBankSearchCondition) !== JSON.stringify(currBankSearchCondition)) {
      // 要异步dispatch， 否则小程序会有问题...
      setTimeout(() => {
        that._reloadProduct(nextBankSearchCondition);
      }, 0)
    }

    // 快速产品搜索条件改变的情况下，重新加载产品
    const nextFastSearchCondition = nextProps.fastSearchCondition
    const currFastSearchCondition = that.props.fastSearchCondition
    if (nextFastSearchCondition && currFastSearchCondition
      && JSON.stringify(nextFastSearchCondition) !== JSON.stringify(currFastSearchCondition)) {
      // 要异步dispatch， 否则小程序会有问题...
      setTimeout(() => {
        that._reloadProduct(nextFastSearchCondition);
      }, 0)
    }
  }

  componentDidMount() {
    this.checkFirstLoad()
  }

  componentWillUnmount() { }

  componentDidShow() {
    // this._initProductFilterFixParam()
  }

  componentDidHide() { }

  render() {
    // const { bankSearchCondition, fastSearchCondition } = this.props
    // console.log('state.searchOption = ', this.state.searchOption)
    // console.log('searchOption = ', searchOption)

    return (
      <View className='product-shop-container'>
        <ScrollView
          scrollY
          scrollWithAnimation
          scrollTop={0}
          lowerThreshold={0}
          style='height: 100vh'
          onScrollToLower={this.onLoadMoreProduct.bind(this)}
          onScroll={this.onViewScroll.bind(this)}>
          {/* 极速贷，银行贷 tab */}
          <View className="product-tab" ref='product-tab-ref'>
            <View className={`product-tab-item ${this.props.activeTabIndex === 0 ? 'active' : ''}`} data-tabid={0} onClick={this.tabItemClick.bind(this)}>
              <Text className="iconfont icon-jinrong text"></Text>
              <Text className="loaction-text text">极速贷</Text>
            </View>
            <View className="divider">
              <Image className="divider-img" src={dividerImg}></Image>
            </View>
            <View className={`product-tab-item ${this.props.activeTabIndex === 1 ? 'active' : ''}`} data-tabid={1} onClick={this.tabItemClick.bind(this)}>
              <Text className="iconfont icon-16 text"></Text>
              <Text className="loaction-text text">银行贷</Text>
            </View>
          </View>
          {/* 极速贷 banner  */}
          {(
            <View className={`fast-product-banner ${this.props.activeTabIndex === 0 ? '' : 'hide'}`}>
              <Image src={bannerImg}></Image>
            </View>
          )}
          {/* 银行贷产品选择分块 */}
          {
            (<View className={`bank-product-box ${this.props.activeTabIndex === 1 ? '' : 'hide'}`}>
              <View className="row">
                <View className="item"
                  data-loadProductType="bank"
                  data-job={1}
                  onClick={this.goToProductFilterList.bind(this, {
                    load_product_type: 'bank',
                    job: 1
                  })}>
                  <View className="circle">
                    <Image className="image" src={workerIcon}></Image>
                  </View>
                  <Text className="text">上班族</Text>
                </View>
                <View className="item"
                  data-loadProductType="bank"
                  data-job={2}
                  onClick={this.goToProductFilterList.bind(this, {
                    load_product_type: 'bank',
                    job: 2
                  })}>
                  <View className="circle">
                    <Image className="image" src={personIcon}></Image>
                  </View>
                  <Text className="text">个体户</Text>
                </View>
                <View className="item"
                  data-loadProductType="bank"
                  data-job={3}
                  onClick={this.goToProductFilterList.bind(this, {
                    load_product_type: 'bank',
                    job: 3
                  })}>
                  <View className="circle" >
                    <Image className="image" src={bossIcon}></Image>
                  </View>
                  <Text className="text">企业主</Text>
                </View>
                <View className="item"
                  data-loadProductType="bank"
                  data-job={4}
                  onClick={this.goToProductFilterList.bind(this, {
                    load_product_type: 'bank',
                    job: 4
                  })}>
                  <View className="circle" >
                    <Image className="image" src={freeIcon}></Image>
                  </View>
                  <Text className="text">自由职业</Text>
                </View>
              </View>
              <View className="row">
                <View className="item"
                  data-loadProductType="bank"
                  data-productType={1}
                  onClick={this.goToProductFilterList.bind(this, {
                    load_product_type: 'bank',
                    product_type: 1
                  })}>
                  <View className="circle" >
                    <Image className="image" src={salaryIcon}></Image>
                  </View>
                  <Text className="text">工薪贷</Text>
                </View>
                <View className="item"
                  data-loadProductType="bank"
                  data-productType={2}
                  onClick={this.goToProductFilterList.bind(this, {
                    load_product_type: 'bank',
                    product_type: 2
                  })}>
                  <View className="circle" >
                    <Image className="image" src={businessIcon}></Image>
                  </View>
                  <Text className="text">生意贷</Text>
                </View>
                <View className="item"
                  data-loadProductType="bank"
                  data-productType={3}
                  onClick={this.goToProductFilterList.bind(this, {
                    load_product_type: 'bank',
                    product_type: 3
                  })}>
                  <View className="circle" >
                    <Image className="image" src={carIcon}></Image>
                  </View>
                  <Text className="text">车抵贷</Text>
                </View>
                <View className="item"
                  data-loadProductType="bank"
                  data-productType={4}
                  onClick={this.goToProductFilterList.bind(this, {
                    load_product_type: 'bank',
                    product_type: 4
                  })}>
                  <View className="circle" >
                    <Image className="image" src={houseIcon}></Image>
                  </View>
                  <Text className="text">房抵贷</Text>
                </View>
              </View>
            </View>)}

          {/* <!-- 快速产品列表分块 --> */}
          {
            (<View className={`product-list-box ${this.props.activeTabIndex === 0 ? 'show' : 'hide'}`}>
              <View key="shop-fast-filter" className="filter-selection-box">
                {/* 必须使用条件渲染，减少计算，提高性能 */}
                { this.props.activeTabIndex === 0 ? 
                  (<ProductFilter
                  inputOption={this.props.fastSearchOption}
                  dispatchActionType={'shop/updateFastSearchCondition'}
                  isNeedFixTop={true} scrollTop={this.state.scrollTop}
                  fixTopY={this.state.filterFixTop || 57} />
                ) : null}
                
              </View>
              <View className="product-list-ct">
                <ProductList
                  dataArray={this.props.fastProductList}
                  userApplyList={this.props.userApplyList}
                  isShowCheck={false} isShowLoanTime={true} isShowApply={true} isShowCollectCancel={false}
                  loading={this.props.effects['shop/searchFast']}
                  noneResult={this.props.fastNoneResult}
                  noneResultTips={this.props.fastNoneResultTips} />
              </View>
            </View>)
          }

          {/* 银行产品列表分块 */}
          {
            <View className={`product-list-box ${this.props.activeTabIndex === 1 ? 'show' : 'hide'}`}>
             {/* 必须使用条件渲染，减少计算，提高性能 */}
              <View key="shop-bank-filter" className="filter-selection-box">
                {this.props.activeTabIndex === 1 ? 
                  (<ProductFilter
                  inputOption={this.props.bankSearchOption}
                  dispatchActionType={'shop/updateBankSearchCondition'}
                  isNeedFixTop={true} scrollTop={this.state.scrollTop}
                  fixTopY={this.state.filterFixTop || 57} />
                ) : null}
                
              </View>
              <View className="product-list-ct">
                <ProductList
                  dataArray={this.props.bankProductList}
                  userApplyList={this.props.userApplyList}
                  isShowCheck={false} isShowLoanTime={true} isShowApply={true} isShowCollectCancel={false}
                  loading={this.props.effects['shop/searchBank']}
                  noneResult={this.props.bankNoneResult}
                  noneResultTips={this.props.bankNoneResultTips} />
              </View>
            </View>
          }

        </ScrollView>

      </View>
    )
  }

  /**
   * 首页滚动到底部触发，加载更多
   * @param e 
   */
  onLoadMoreProduct(e) {

    if (this.props.activeTabIndex === 0) {
      if (this.props.effects['shop/searchFast']) {
        console.log('加载数据中，return !!!', e)
        return
      }
    } else if (this.props.activeTabIndex === 1) {
      if (this.props.effects['shop/searchBank']) {
        console.log('加载数据中，return !!!', e)
        return
      }
    }

    this._loadMoreProduct()
    console.log('滚动到底部，加载更多', e)
  }

  /**
   * 页面滚动监视方法
   * @param e 
   * e 例子： event.detail = {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY}
   */
  onViewScroll(e) {
    // console.log('首页滚动, e = ', e.detail)
    // 更新 scrollTop
    this.setState({
      scrollTop: e.detail.scrollTop,
    })
  }

  /**
   * 重新加载产品
   */
  _reloadProduct(condition?: any) {

    const { activeTabIndex, bankLastLoadTime, fastLastLoadTime,
      fastSearchCondition, bankSearchCondition } = this.props

    if (activeTabIndex === 0) {

      if (!isTimeIntervalValid(fastLastLoadTime)) {
        return
      }
      const searchCondition = condition || fastSearchCondition
      this.props.searchFast({
        ...searchCondition,
        page: 1,
      })
    } else if (activeTabIndex === 1) {

      if (!isTimeIntervalValid(bankLastLoadTime)) {
        return
      }
      const searchCondition = condition || bankSearchCondition
      this.props.searchBank({
        ...searchCondition,
        page: 1,
      })
    }
  }

  /**
   * 加载更多产品
   * 加载下一页数据
   */
  _loadMoreProduct() {
    const { activeTabIndex, bankLastLoadTime, fastLastLoadTime,
      bankProductPage, fastProductPage, defaultPageSize, fastProductList, bankProductList,
      fastSearchCondition, bankSearchCondition } = this.props

    if (activeTabIndex === 0) {

      if (!isTimeIntervalValid(fastLastLoadTime)) {
        return
      }
      const searchCondition = fastSearchCondition
      this.props.searchFast({
        ...searchCondition,
        page: getNextPage(fastProductPage, defaultPageSize, fastProductList.length)
      })
    } else if (activeTabIndex === 1) {

      if (!isTimeIntervalValid(bankLastLoadTime)) {
        return
      }
      const searchCondition = bankSearchCondition
      this.props.searchBank({
        ...searchCondition,
        page: getNextPage(bankProductPage, defaultPageSize, bankProductList.length)
      })
    }
  }

  /**
   * tab点击处理方法
   * @param e 
   */
  tabItemClick(e) {
    //防止点击过快带来的闪屏问题
    let timestamp = new Date().getTime()
    timestamp = timestamp / 1000
    const data = e.currentTarget.dataset
    const that = this

    if (cont_time) {
      if (timestamp - cont_time >= 1) {
        that.nextpic(data.tabid);
        cont_time = timestamp;
      } else {
        cont_time = timestamp;
      }
    } else {
      that.nextpic(data.tabid);
      cont_time = timestamp;
    }

    console.log('tabItemClick, tabid = ', data.tabid)
  }

  /**
   * 切换极速贷，银行贷tab的处理方法
   * @param {number} tabIndex 选中的tab下标
   */
  nextpic(tabIndex) {
    this.props.saveTabIndex(parseInt(tabIndex))

    // 暂时没有什么好方法能在dispatch后回调 this.checkFirstLoad() 
    // 使用定时器也可以达到这种效果
    setTimeout(() => {
      this.checkFirstLoad()
    }, 0)
  }

  /**
   * 检查是否第一次加载快速产品或银行产品，
   * 是则根据选中的tab加载对应的数据
   */
  checkFirstLoad() {
    // 检查是否已加载过快速产品或银行产品，如果没加载过，则根据当前tab加载对应的产品
    if (this.props.fastProductList.length === 0
      || this.props.bankProductList.length === 0) {
      this._reloadProduct()
    }
  }

  /**
   * 跳转到产品过滤列表页面的方法
   * @param param 跳转参数
   * @param e
   */
  goToProductFilterList(param: any, e) {
    // 跳转到产品过滤列表页面
    const productFilterUrl = '/pages/productFilterList/index'
    Taro.navigateTo({
      url: utils.getUrlWithParam(productFilterUrl, param)
    })
  }

  /**
   * 初始化过滤组件的固定定位参数
   */
  _initProductFilterFixParam() {
    // 微信小程序
    if (Taro.getEnv() === Taro.ENV_TYPE.WEAPP) {
      setTimeout(() => {
        const query = Taro.createSelectorQuery().in(this.$scope)
        query.select('.product-tab')
          .boundingClientRect()
          .exec(res => {
            // console.log('product-tab res = ', res)
            if (Array.isArray(res) && res.length > 0) {
              this.setState({
                filterFixTop: res[0]['height'],
              })
            }
          })
      }, 100)
    } else if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
      // h5 要延时获取组件高度，否则高度会有问题...
      setTimeout(() => {
        const element = this.refs['product-tab-ref']
        console.log('element.vnode.dom.clientHeight = ', element.vnode.dom.clientHeight)
        if (element) {
          this.setState({
            filterFixTop: element.vnode.dom.clientHeight
          })
        }
        console.log('web element = ', element)
      }, 100)
    }
  }
}
// #region 导出注意
//
// 经过上面的声明后需要将导出的 Taro.Component 子类修改为子类本身的 props 属性
// 这样在使用这个子类时 Ts 才不会提示缺少 JSX 类型参数错误
//
// #endregion

export default Shop as ComponentClass<PageOwnProps, PageState>
